package com.itheima.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.mapper.SkuMapper;
import com.itheima.leyou.po.Sku;
import com.itheima.leyou.service.SkuService;
import com.leyou.item.dto.SkuDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Override
    public List<SkuDTO> querySkuByspuId(Long id) {
        List<Sku> skuList = this.query().eq("spu_id", id).list();
        return SkuDTO.convertEntityList(skuList);
    }

    @Override
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        return SkuDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    @Transactional
    public void deleteSpuBySku(SkuDTO skuDTO) {
        Sku sku = baseMapper.selectStockById(skuDTO.getId());
        Integer stock = sku.getStock();
        if (stock <= 0) {
            return;
        }
        System.out.println("库存=" + stock);
        Random random=new Random();
        int num = random.nextInt(999)+1;//随机生成1-1000的一个随机数
        if(sku.getStock()-num<=0){
            return;
        }
        sku.setStock(sku.getStock() - num);
        this.save(sku);
        System.out.println("库存成功减 "+num+" 数据库的库存为" + sku.getStock());
    }
}
